from utils import service_functions
from template.singleton import Singleton


class Сommunication_wrapper:
    def __init__(self, obj_communication, obj_wrapper_calls_fun) -> None:
        self.obj_communication = obj_communication
        self.obj_wrapper_calls_fun = obj_wrapper_calls_fun

    def __iter_list_mess(self, list_mess):
        try:
            for mess in list_mess:
                self.obj_communication.message(mess)
        except BaseException:
            self.obj_communication.message("Ошибка идексов модулей сообщений")

    def __list_menu(self, list_mess):
        exit_flag = False
        iter_step = 5
        iter_mess = 0
        num = -1
        len_data = len(list_mess)
        while not exit_flag:
            iter_mess, iter_step = service_functions.iterator(
                iter_mess, len_data, iter_step
            )
            typle_key_num = self.obj_wrapper_calls_fun.key_or_num()
            if iter_step > 0:
                self.__iter_list_mess(list_mess[iter_mess : iter_mess + iter_step])
            else:
                self.__iter_list_mess(list_mess[iter_mess + iter_step : iter_mess])
            permission_key = typle_key_num[0]
            num = typle_key_num[1]
            if permission_key:
                if permission_key == "forward":
                    iter_mess += iter_step
                elif permission_key == "back":
                    iter_mess -= iter_step
                elif permission_key == "metka_end":
                    exit_flag = True
            elif num != -1:
                exit_flag = True

            iter_mess += iter_step
        return num

    def message_typle(self, mess_typle):
        if mess_typle is not None:
            if mess_typle:
                if isinstance(mess_typle, str):
                    self.__scheduler_message(("str_mess", mess_typle))
                elif isinstance(mess_typle, tuple):
                    self.__scheduler_message(mess_typle)
                else:
                    pass

    def __scheduler_message(self, message_tuple):
        if isinstance(message_tuple, tuple):
            if len(message_tuple) > 1:
                type_mess = message_tuple[0]
                mess = message_tuple[1]
                if type_mess == "str_mess":
                    self.obj_communication.message(mess)
                elif type_mess == "dict_menu":
                    self.obj_wrapper_calls_fun.menu_dict_mess(mess)
                elif type_mess == "list_mess":
                    self.__list_menu(mess)
                elif type_mess == "html_mess":
                    pass
                elif type_mess == "dict_html_and_mess":
                    # key1: mess_str
                    # key2: html
                    # key3: ???
                    pass
                elif type_mess == "api":
                    pass
